package com.sy.olddriver.utils;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库操作工具类
 *
 * @author Administrator
 */
public class DbUtils {
    private static Properties properties;

    /**
     * 采用ThreadLocal来保存一个线程中多次Jdbc操作要用到的连接对象
     * 因为如果要进行事务管理，需要保证多个Jdbc操作中持有的是同一个连接对象
     */
    private static ThreadLocal<Connection> curCon = new ThreadLocal<>();

    static {
        properties = PropertiesUtils.loadProperties("db.properties");
        org.apache.commons.dbutils.DbUtils.loadDriver(properties.getProperty("driver"));
    }

    public static Connection getConnection() {
        //先从ThreadLocal中获取连接对象
        Connection con = curCon.get();
        if (null == con) {
            try {
                con = DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("user"), properties.getProperty("pwd"));
            } catch (SQLException e) {
                e.printStackTrace();
            }
            curCon.set(con);
        }
        return con;
    }

    /**
     * 关闭当前的连接对象，并从ThreadLocal中移除
     */
    public static void close() {
        Connection con =getConnection();
        if (null != con) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            curCon.remove();
        }
    }

    /**
     * 开启事务
     */
    public static void beginTx() {
        Connection con = getConnection();
        if (null != con) {
            try {
                con.setAutoCommit(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 提交事务
     */
    public static void commit() {
        Connection con = getConnection();
        if (null != con) {
            try {
                con.commit();
                con.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 回滚事务
     */
    public static void rollback() {
        Connection con = getConnection();
        if (null != con) {
            try {
                con.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
